﻿using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;

namespace WXWorkAPI_V1
{
    public class WxwCFG
    {
        public const string sToken = "VagZSSP9icudw";
        public const string sCorpID = "ww3521e4dd5090a42e"; // 湖北洪城通用机械有限公司
        public const string sEncodingAESKey = "O8lqMtAUwOJcQto6eeuwg23IaqAmVWKcx5Q3dEnPzq5";

        public const string sTcpServerIp = "111.4.57.249";
        public const int iTcpServerPort = 8592;
        public const int iSendTimeoutMs = 2000;    // 发送超时时间(毫秒)


        public async Task SendToTcpServerAsync(string data)
        {
            using var client = new TcpClient();
            // 连接并设置超时
            await client.ConnectAsync(sTcpServerIp, iTcpServerPort);
            client.SendTimeout = iSendTimeoutMs;

            using var stream = client.GetStream();
            var requestBytes = Encoding.UTF8.GetBytes(data);

            // 发送数据
            await stream.WriteAsync(requestBytes, 0, requestBytes.Length);
            await stream.FlushAsync();
        }

        public static void thdSendToTcpServer(string SendDatas)
        {
            Thread tSendThd = new Thread(() =>
            {
                string tSendDatas = SendDatas;
                using (TcpClient client = new TcpClient())
                    try
                    {
                        // 创建一个异步连接操作
                        IAsyncResult result = client.BeginConnect(
                            IPAddress.Parse(sTcpServerIp), iTcpServerPort, null, null);

                        // 等待连接操作完成，或超时
                        bool success = result.AsyncWaitHandle.WaitOne(iSendTimeoutMs, false);

                        if (success)
                        {
                            // 完成连接操作
                            client.EndConnect(result);
                            //Console.WriteLine("连接成功！");
                            // 获取网络流并发送数据
                            using (NetworkStream stream = client.GetStream())
                            {
                                byte[] sendBuf = Encoding.UTF8.GetBytes(tSendDatas);
                                stream.Write(sendBuf, 0, sendBuf.Length);
                                /*
                                // 可选：接收服务器响应
                                byte[] buffer = new byte[1024];
                                int bytesRead = stream.Read(buffer, 0, buffer.Length);
                                string response = Encoding.UTF8.GetString(buffer, 0, bytesRead);
                                Console.WriteLine($"收到响应: {response}");
                                */
                            }
                        }
                    }
                    finally
                    {
                        client.Close();
                    }
            });
            tSendThd.Start();
        }
    }
}
